<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>项目反馈</title>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <style>
        .imgslist{width:60px;height:60px;margin:3px}
        #img_wrap{min-height: 120px}
        #uploadInfo{font-weight: bold}
    </style>

    <%--<script src="../resource/wechat/jweixinapi.js"></script>--%>
    <jsp:include page="../../../main/mp/inc.jsp"	/>
    <script>
        $(function(){
            //alert(location.href.split('#')[0]);
            $("[data-role='navbar']").navbar();
            $("[data-role='header'], [data-role='footer']").toolbar();
        });

        $(function(){
            var currYear = (new Date()).getFullYear();
            var opt={};
            opt.date = {preset : 'date'};
            opt.datetime = {preset : 'datetime'};
            opt.time = {preset : 'time'};
            opt.default = {
                theme: 'android-ics light', //皮肤样式
                display: 'modal', //显示方式
                mode: 'scroller', //日期选择模式
                animate:'swing',
                lang:'zh',
                startYear:currYear - 10, //开始年份
                endYear:currYear + 10 //结束年份
            };

            var optDateTime = $.extend(opt['datetime'], opt['default']);
            $("#backDate").val('<s:date name="proBack.backDate" format="yyyy-MM-dd" />').scroller('destroy').scroller($.extend(opt['date'], opt['default']));

            $("#btn-save-common").click(function(e){
                if($("select[name=dictId]").val()==""){
                    alert("请选择反馈类别");
                    return;
                }
                if($("#backDate").val()==""){
                    alert("请选择反馈日期");
                    return;
                }

                $("#wxMediaIds").val("");
                if(parseInt($("#wxMediaLength").val())>0){
                    $("#uploadInfo").show();
                    $('#uploadImage_btn').click();
                }else{
                    save_from();
                }

            });
        });

        function myConfirm(t, c, fn) {
            $("#popupConfirm h1").html(t);
            $("#popupConfirm p").html(c);
            $("#popupConfirm a:contains('是')").unbind("click").click(function() {$("#confirmResult").val("1"); $("#popupConfirm").popup("close"); });
            $("#popupConfirm a:contains('否')").unbind("click").click(function() {$("#confirmResult").val("0"); $("#popupConfirm").popup("close"); });
            if (fn) $("#popupConfirm").unbind("popupafterclose").bind("popupafterclose", function() { fn(); });
            $("#popupConfirm").popup("open");
        }

        function save_from(){
            myConfirm("系统提示","确定提交反馈吗?",function(){
                if($("#confirmResult").val()==="1"){
                    $("#btn-save-common").hide();
                    $.mobile.loading( "show", {
                        text: "正在保存，请稍后...",
                        textVisible: true,
                        theme: "b",
                        textonly: false,
                        html: ""
                    });
                    $.ajax({
                        type: "POST",
                        url: $("form#form-common").attr("action"),
                        cache:false,dataType:"json",
                        data: $("form#form-common").serialize(),
                        async:false,
                        success: function(data){
                            if(data.state == "200"){
                                hide();
                                location.replace("ajax-proinfo!read.action?keyId=" + data.title);
                            }else{
                                $("#btn-save-common").show();
                                alert(data.message);
                            }
                        }
                    });
                }else{
                    $("#popupConfirm").popup("close");
                }
            });

        }

    </script>
</head>
<body>
<!-- class="jqm-demos" -->
<div data-role="page" >
    <div data-role="header" data-position="fixed" data-theme="a">
        <h1 style="float:left;margin: 0 10px;color: #121010;"><i class="fa fa-user"></i> 项目反馈</h1>
        <a href="#" id="btn-save-common" class="ui-btn ui-btn-right ui-icon-check ui-corner-all ui-btn-icon-left">保存</a>
    </div><!-- /header -->
    <div class="ui-content jqm-content jqm-fullwidth" role="main">
        <form id="form-common" method="post" id="form-common" action="ajax-proback!save.action" data-ajax="false">
            <input type="hidden" name="keyId" id="keyId" value="<s:property value="proBack.id" />"/>
            <input type="hidden" name="wxMediaIds" id="wxMediaIds" />
            <input type="hidden" id="latitude" name="latitude" value="" />
            <input type="hidden" id="longitude" name="longitude" value="" />
            <input type="hidden" id="wxMediaLength" value="0"/>
            <input type="hidden" id="confirmResult" value="0"/>
            <div id="uploadInfo" style="display: none">
            </div>
            <div class="ui-field-contain">
                <label>项目名称：</label>
                <s:property value="proBack.proInfo.name"/>
                <input type="hidden" id="proInfoId" name="proInfoId" value="<s:property value="proInfoId"/>"/>

            </div>
            <div class="ui-field-contain">
                <label>反馈类别：</label>
				    
                        <select name="dictId">
                            <option value="">请选择</option>
                            <s:iterator value="typesArrayList" id="list" >
                                <option  value="<s:property value="#list.id"/>" <s:property value="#list.selected"/> ><s:property value="#list.name"/></option>
                            </s:iterator>
                        </select>
                    
            </div>

            <div class="ui-field-contain">
                <label>反馈日期：</label>
                <input type="date" id="backDate" name="backDate" value="<s:property value="proBack.backDate"/> " />
            </div>
            <div class="ui-field-contain">
                <label>反馈内容：</label>
                <input type="text" id="content" name="content" value="<s:property value="proBack.content"/>">
            </div>
            <div class="ui-field-contain">
                <label>备注：</label>
                <span ><input type="text" id="mark" name="mark" value="<s:property value="proBack.mark"/>">
            </div>
            <div class="ui-field-contain">
                <label>是否正常：</label>
                <table style="width: 100%">
                    <tr>
                        <td style="width: 50%">
                            <input style="margin-top:0" type="radio" name="regular" id="regularY" class="custom" value="1" <s:if test='proBack.id!=null && proBack.regular==1'>checked</s:if>> <span style="margin-left:40px">是
                        </td>
                        <td>
                            <input style="margin-top:0" type="radio" name="regular" id="regularN" class="custom" value="0" <s:if test='proBack.id!=null && proBack.regular==0'>checked</s:if>> <span style="margin-left:40px">否
                        </td>
                    </tr>
                </table>
            </div>

            <div class="ui-field-contain">
                <label>通知人员：</label>
                <select name="noticeId" id="noticeId" multiple>
                    <s:iterator value="userListMap.keySet()" id="list">
                        <optgroup label="<s:property value="#list"/>">
                            <s:iterator value="userListMap.get(#list)" id="user">
                                <option value="<s:property value="#user.id"/>" <s:property value="#user.selected"/> > <s:property value="#user.name" /> </option>
                            </s:iterator>
                        </optgroup>
                    </s:iterator>
                </select>
            </div>
            <s:if test="hasImgs==1">
                <div class="ui-field-contain">
                    <label>已上传照片列表：</label>
                    <s:iterator value="imgUrl" id="url">
                        <img class="imgslist" width="300" src="<s:property value="#url" />">
                    </s:iterator>
                </div>
            </s:if>
        </form>
        <div class="ui-field-contain">
            <label >拍照上传【最多9张】：</label>
                
                    <button class="btn" id="chooseImage_btn">选择照片</button>
                
                 
                    <button class="btn" id="uploadImage_btn" style="display:none">上传照片</button>
                
        </div>
        <div class="ui-field-contain">
            <label >照片列表【点击删除】：</label>
            <div id="img_wrap">
                <%--<img id="imgPreview0" style="width:300px;height:300px;margin:3px;display:inline" data-index="0" src="weixin://resourceid/4d9ea5a5577598b8a7dad66016a96129">--%>
                <img id="imgPreview0" style="width:60px;height:60px;margin:3px;display:none" data-index="0">
                <img id="imgPreview1" style="width:60px;height:60px;margin:3px;display:none" data-index="1">
                <img id="imgPreview2" style="width:60px;height:60px;margin:3px;display:none" data-index="2">
                <img id="imgPreview3" style="width:60px;height:60px;margin:3px;display:none" data-index="3">
                <img id="imgPreview4" style="width:60px;height:60px;margin:3px;display:none" data-index="4">
                <img id="imgPreview5" style="width:60px;height:60px;margin:3px;display:none" data-index="5">
                <img id="imgPreview6" style="width:60px;height:60px;margin:3px;display:none" data-index="6">
                <img id="imgPreview7" style="width:60px;height:60px;margin:3px;display:none" data-index="7">
                <img id="imgPreview8" style="width:60px;height:60px;margin:3px;display:none" data-index="8">
            </div>
        </div>

        <div data-role="popup" id="popupConfirm" data-inline="true" data-position-to="window"
             data-theme="a" style="max-width:400px;" class="ui-corner-all">
            <div data-role="header" data-theme="b" class="ui-corner-top">
                <h1></h1>
            </div>
            <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
                <p style="width:350px;"></p>
                <div style="text-align: center">
                    <a href="#" data-role="button" data-mini="true" data-inline="true" data-transition="flow" data-theme="c">是</a>
                    <a href="#" data-role="button" data-mini="true" data-inline="true" data-transition="flow" data-theme="c">否</a>
                </div>
            </div>
        </div>

    </div><!-- /content -->
</div><!-- /page -->

<script>
    //        function sleep(n) {
    //            var start = new Date().getTime();
    //            while(true)  if(new Date().getTime()-start > n) break;
    //        }

    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: '<s:property value="jsapiSignature.appId" />', // 必填，公众号的唯一标识
        timestamp: '<s:property value="jsapiSignature.timestamp" />', // 必填，生成签名的时间戳
        nonceStr: '<s:property value="jsapiSignature.noncestr" />', // 必填，生成签名的随机串
        signature: '<s:property value="jsapiSignature.signature" />',// 必填，签名，见附录1
        jsApiList: ['checkJsApi', 'chooseImage', 'previewImage','uploadImage','downloadImage','getLocation'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    wx.ready(function() {
        // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
//            document.querySelector('#checkJsApi').onclick = function () {
//                wx.checkJsApi({
//                    jsApiList: [
//                        'chooseImage','previewImage', 'uploadImage','downloadImage'
//                    ],
//                    success: function (res) {
//                        alert(JSON.stringify(res));
//                    }
//                });
//            };
        // 5 图片接口
        var images = {
            localId: [],
            serverId: []
        };

        wx.getLocation({
            success: function (res) {
                $("input#latitude").val(res.latitude);
                $("input#longitude").val(res.longitude);
            },
            error : function(){
                alert("获取位置失败，请确认是否开启GPS定位功能!");
            }
        });
        // 5.1 拍照、本地选图
        document.querySelector('#chooseImage_btn').onclick = function () {
            //images.localId = [];
            wx.chooseImage({
                success: function (res) {
//                      alert("res:"+res.localIds.join(","));
//                      for (var i in res) alert(i + ':' + res[i]);
//                      sleep(1000);
                    var len1 = res.localIds.length;
                    //alert("本次共选择了"+len1+"张照片！");
                    var len2 = images.localId.length;
                    //alert("len1:"+len1 + " len2:" + len2);
                    var len = len1+len2;
                    if (len > 9) {
                        alert('选择要上传的图片不能超过9张！');
                        return;
                    }
                    if(images.localId.length==0){
                        images.localId = res.localIds;
                    }else{
                        images.localId = images.localId.concat(res.localIds);
                    }
                    //alert("images.localId len:"+images.localId.length);
                     reloadImgs();

                    $("#wxMediaLength").val(len);
                    //syncUpload();
                    res.localIds = [];
                }
            });
        };

        function reloadImgs() {
            var len = images.localId.length;
           // alert("len:"+len);
            for(var i=0;i<9;i++){
                var imgE = $("#imgPreview"+i).first();
                //imgE.attr("src","").hide().off("click");
                //imgE.attr("src",id).show();
                if(i<len){
                    var id = images.localId[i];
                    //alert(id);
                    imgE.attr("src",id).show().on("click",function(event){
                        if(!confirm("确定要删除该图片吗？")){
                            return;
                        }
                        $(this).attr("src","").hide().off("click");
                        var idx = $(this).attr("data-index");
                        images.localId.splice(idx,1);
                        var l = parseInt($("#wxMediaLength").val() - 1);
                        $("#wxMediaLength").val(""+l);
                       // reloadImgs();
                       // event.stopPropagation();
                    });
                }
            }
        }

        document.querySelector('#uploadImage_btn').onclick = function () {
            syncUpload();
        };
        // 5.2 上传图片
        function syncUpload() {
            var i = 0, length = images.localId.length;
            if (length > 9) {
                alert('要上传的图片不能超过9张！');
                return;
            }
            images.serverId = [];
            function upload() {
                wx.uploadImage({
                    localId: images.localId[i],
                    isShowProgressTips: 1,
                    success: function (res) {
                        i++;
//                        alert('已上传第' + i + '张照片，共' + length + '张照片');
//                        $("#uploadInfo").text('上传照片进度：已上传第' + i + '张照片，共' + length + '张照片');
                        var ids = $("#wxMediaIds").val();
                        if(ids.length>0){
                            ids += ",";
                        }
                        ids += res.serverId;
                        $("#wxMediaIds").val(ids);
                        images.serverId.push(res.serverId);
                        if (i < length) {
                            upload();
                            //setTimeout(upload(),100);
                        }else{
                            //alert('图片已上传成功！');
                            //alert($("#wxMediaIds").val());
                            save_from();
                        }}
                    ,
                    fail: function (res) {
//                      alert(JSON.stringify(res));
                        i++;
//                        alert('上传第' + i + '张照片失败，请稍后重新点击保存按钮');
                        $("#uploadInfo").text('上传第' + i + '张照片失败，请稍后重新点击保存按钮').show();
                        return false;
                    }
                });
            }
            upload();
        };

    });

    wx.error(function(res){
        alert(JSON.stringify(res));
    });

</script>
<script type="text/javascript">
    $(function () {

        $('#noticeId').mobiscroll().select({
            theme: 'android-ics light',
            display: 'bottom',
            label: '请选择人员',
            lang: 'zh',
            group: true,
            groupLabel: ' '
        });
        $("#noticeId-button>span").hide();
        $("#noticeId-button").removeClass("ui-icon-carat-d ui-btn-icon-right");
    });

</script>
</body>
</html>